package service.script;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;

import org.apache.log4j.Logger;

import communication.MessageHelper;
import communication.ParameterizedMessage;
import communication.ParameterizedMessageImpl;

import scriptrunner.execution.ExecuteErrorException;
import scriptrunner.execution.FunctionRegister;
import scriptrunner.execution.parameter.Parameter;
import scriptrunner.parser.Lexer;
import scriptrunner.parser.parser;
import service.AbstractService;
import service.ServiceRequestHandler;

public class ScriptExecutionRequestHandler extends ServiceRequestHandler {
	
	private Logger logger = Logger.getLogger(ScriptExecutionRequestHandler.class);

	public ScriptExecutionRequestHandler(AbstractService service) {
		super("ScriptExecutionService::Execute", service);
	}

	@Override
	public ParameterizedMessage handle(ParameterizedMessage message) {
		logger.debug("Received new request message");
		Parameter<String> httpParameter = (Parameter<String>) message.getAttachment();
		String script = message.getParameter("script");
		logger.debug("Http parameter: " + httpParameter.toString());
		logger.debug("Script: " + script);
		
		parser p = new parser( new Lexer( new ByteArrayInputStream(script.getBytes()) ) );
		
		ParameterizedMessage retMsg = new ParameterizedMessageImpl("executeResult");
		
		try {
			p.parse();
		} catch (Exception e) {
			MessageHelper.markAsFailed(retMsg, e);
			return retMsg;
		}
		
		scriptrunner.execution.Session se = new scriptrunner.execution.Session(httpParameter);
		try {
			FunctionRegister.GetInstance().GetMainFunction().Execute(se);
		} catch (ExecuteErrorException e) {
			MessageHelper.markAsFailed(retMsg, e);
			return retMsg;
		}
		
		scriptrunner.execution.ValueObject v = se.getReturnResult();
		
		MessageHelper.markAsSuccess(retMsg, v);
		
		return retMsg;
	}

}
